// Ajax form请求模拟下载
jQuery.jdownload = function(url, data, method) {
	jQuery("#down_div").removeClass("xhide");
		jQuery("#over_div").removeClass("xhide");
	// 获取url和data
	if (url && data) {
		// data 是 string 或者 array/object
		data = typeof data == 'string' ? data : jQuery.param(data);
		// 把参数组装成 form的 input
		var inputs = '';
		jQuery.each(data.split('&'), function() {
			var pair = this.split('=');
			inputs += '<input type="hidden" name="' + pair[0] + '" value="'
					+ pair[1] + '" />';
		});
		// request发送请求
		jQuery(
				'<form action="' + url + '" method="' + (method || 'post')
						+ '">' + inputs + '</form>').appendTo('body').submit()
				.remove();
		jQuery("#down_div").addClass("xhide");
		jQuery("#over_div").addClass("xhide");
	}
	;
};

function exportSubmit(url,flag){
//	 var token=jQuery("#mytoken").val();
//	 var exportUrl=jQuery("#excelUrl").attr("exportUrl");
//	 if(typeof(exportUrl)=='undefined'){
//		 alert("请选择导出选项");
//		 return;
//	 }
//	 jQuery("#down_div").removeClass("xhide");
//	 jQuery("#over_div").removeClass("xhide");
	 var type=url.substring(url.lastIndexOf("/")+1);
//	 var  eurl='?token='+token;
	
      if(flag==1){
    	  url+='?isData=1';
//			setTimeout("closeWait()", 2500);
	 }else{
//			setTimeout("closeWait()", 1500);
		
	 } 
	 jQuery.jdownload(url,'type="'+type+'"','post' );
}

 function importSubmit(o) {
		var form = jQuery('#form');
		var $file = jQuery(o).clone();
		 var token=jQuery("#mytoken").val();
		 var importUrl=jQuery("#excelUrl").attr("importUrl");
		 var str=importUrl.substring(importUrl.lastIndexOf("/")+1);
		 importUrl=importUrl+"?token="+token;
		 if(typeof(importUrl)=='undefined'){
			  alertred("请选择导入选项",'系统提示',null,function(){
				});
			 return;
		 }
		 var fileUrl=jQuery("#excelFile").val();
		 if(fileUrl==""){
			  alertred("请选择导入的文件",'系统提示',null,function(){
				});
			 return;
		 }
		 
		 jQuery("#down_div").removeClass("xhide");
			jQuery("#over_div").removeClass("xhide");
		 form.attr("action",importUrl);
			var options = {
				dataType : "json",
				global:true,
				beforeSubmit : function() {
					
				},
				success : function(result) {
					jQuery("#down_div").addClass('xhide');
					jQuery("#over_div").addClass('xhide');
					  if(result.result){
						  jQuery('#addModal').modal('hide');
						  ipos = importUrl.indexOf('?');
						  importUrl = importUrl.substring(0,ipos);
						  var curObject=jQuery(".radiobox input[value='"+importUrl+"']");
							var id=curObject.attr("id");
							 var index=parseInt( id.substring("import".length,id.length));
							 importUrl=importUrl.substring(importUrl.lastIndexOf("/")+1);
						if( updateImportJsonData(index,importUrl)){
							if(index>=maxIndex){
						    maxIndex=index;
						    maxImportUrl=importUrl;
							}
						    curObject.next().addClass("checked");
						}
						  alertgreen(result.message,'系统提示',null,function(){
							 
							}); 
						  
					  }else if(result.url=='tokenError'){
							alertred(result.message, '系统提示', null, function() {
								window.location.href = "${ctx}/login/logout";
							});
						  
					  }else if(result.url!="dataError"){
						  alertred(result.message,'系统提示',"下载",function(){
							  var fileName=encodeURIComponent(result.url);
								 jQuery.jdownload("${ctx}/sysInit/download","fileName="+result.url+"","post");
//                                     alert(result.url);
//							 window.open('${ctx}'+result.url, '下载失败excel', 'height=400, width=600, top=200, left=600, toolbar=0, menubar=0, scrollbars=0, resizable=0, location=0, status=0');  
							});
					  }else {
						  alertred(result.message,'系统提示',null,function(){
	 						});
					  }
					 
				},
				error : function(result) {
					jQuery("#down_div").addClass('xhide');
					jQuery("#over_div").addClass('xhide');
//					console.log("error"+result);
				}
			};
			form.ajaxSubmit(options);
		} 

$(function () {
//	jQuery("#down_div").removeClass("xhide");
//	jQuery("#over_div").removeClass("xhide");
	
	 new AjaxUpload('#import', {
	        action: baseURL + 'pro/deviceInitExcel/importDeviceInitExcel?token=' + token,
	        name: 'excelFile',
	        autoSubmit:true,
	        type: 'POST',
	        responseType:"json",
	        onSubmit:function(file, extension){
	        /*    if(vm.config.type == null){
	                alert("云存储配置未配置");
	                return false;
	            }*/
	            if (!(extension && /^(xlsx)$/.test(extension.toLowerCase()))){
	                alert('只支持excle ,.xlsx文件！');
	                return false;
	            }
	            
	   		 jQuery("#down_div").removeClass("xhide");
	   			jQuery("#over_div").removeClass("xhide");
	        },
	        onComplete : function(file, r){
	        	
	        	jQuery("#down_div").addClass('xhide');
				jQuery("#over_div").addClass('xhide');
//	        	i.ResponseUtils.buildResultJson(Boolean result, String message, String url)
	            if(r.result){
	                alert(r.message);
	                vm.reload();
	            }else{
	            	
	            	if(r.url!='dataError'){
	            		alert(r.message, function(){
	            			var fname=r.url.substring(r.url.lastIndexOf("/")+1);
	            			 jQuery.jdownload(r.url,"fileName="+r.url+"","get");
	            			 vm.reload();
	            		});
	            	}else{
	            		alert(r.message, function(){
	            			vm.reload();
	            		});
	            	}
	            	 
	            }
	        }
	    });
    $("#jqGrid").jqGrid({
        url: baseURL + 'pro/deviceInit/list',
        datatype: "json",
        colModel: [			
			{ label: '初始数据ID', name: 'id_', width: 45, key: true },
            { label: '所属组织', name: 'deptName', width: 75 },
			{ label: '病区名称', name: 'sickAreaName', width: 75},
			{ label: '设备SN号', name: 'deviceSN', width: 75 },
			{ label: '床位号', name: 'bedNO', width: 75 },
			/* { label: '邮箱', name: 'email', width: 90 },
			{ label: '手机号', name: 'mobile', width: 80 },
			{ label: '状态', name: 'status', width: 80, formatter: function(value, options, row){
				return value === 0 ? 
					'<span class="label label-danger">禁用</span>' : 
					'<span class="label label-success">正常</span>';
			}}, */
			{ label: '时间', name: 'updateTime', width: 90}
/* 			{ label: '时间', name: 'createTime', index: "create_time", width: 90} */
        ],
		viewrecords: true,
        
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var settingSick = {
	    data: {
	        simpleData: {
	            enable: true,
	            idKey: "deptId",
//	            pIdKey: "null",
	            rootPId: -1
	        },
	        key: {
	            url:"nourl"
	        }
	    }
	};
var ztree;
var ztreeSick;

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			bedNO: null
		},
		showList: true,
		title:null,
		pro:{
			/*deptId:null,
            deptName:null,
            sickAreaNO:null,
            sickAreaName:null*/
			 
		}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.pro = {deptName:null, deptId:null, sickAreaNO:null,sickAreaName:null};
			vm.getDept();

		},
        getDept: function(){
            //加载组织树,非病区
            $.get(baseURL + "sys/dept/listNotSick", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r);
                var node = ztree.getNodeByParam("deptId", vm.pro.deptId);
                if(node != null){
                    ztree.selectNode(node);
                    vm.pro.deptName = node[0].name;
                	vm.pro.deptId=node[0].deptId;
                   
				}
            })
        },
        getDeptUpdate: function(){
        	//加载组织树,非病区
        	$.get(baseURL + "sys/dept/listNotSick", function(r){
        		ztree = $.fn.zTree.init($("#deptTree"), setting, r);
        		var node = ztree.getNodeByParam("deptId", vm.pro.deptId);
        		if(node != null){
        			ztree.selectNode(node);
        			vm.pro.deptName = node.name;
        			vm.pro.deptId=node.deptId;
        			/*vm.pro.sickAreaNO=node.sickAreaNO;
        			vm.pro.sickAreaName=node.sickAreaName;*/
        			
        		}
        	})
        },
        getDeptSick: function(){
        	if(vm.pro.deptId==null){
        		alert("请先选择组织");
        		return;
        	}
            //加载组织树
            $.get(baseURL + "sys/dept/listSick/"+vm.pro.deptId+"", function(r){
            	ztreeSick = $.fn.zTree.init($("#deptTreeSick"), settingSick, r);
                var node = ztreeSick.getNodeByParam("deptId", vm.pro.sickAreaNO);
                if(node!=null){
                	ztreeSick.selectNode(node);
                	vm.pro.sickAreaNO=node[0].sickAreaNO;
                	vm.pro.sickAreaName=node[0].name;
                   
                }
                   
            })
        },
        getDeptSickUpdate: function(){
        	if(vm.pro.deptId==null){
        		alert("请先选择组织");
        		return;
        	}
        	//加载组织树
        	$.get(baseURL + "sys/dept/listSick/"+vm.pro.deptId+"", function(r){
        		ztreeSick = $.fn.zTree.init($("#deptTreeSick"), settingSick, r);
        		var node = ztreeSick.getNodeByParam("deptId", vm.pro.sickAreaNO);
        		if(node!=null){
        			ztreeSick.selectNode(node);
        			vm.pro.sickAreaNO=node.deptId;
        			vm.pro.sickAreaName=node.name;
        			
        		}
        		
        	})
        },
		update: function () {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			
			vm.showList = false;
            vm.title = "修改";
			
			vm.getPro(id);
			
		},
		del: function () {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "pro/deviceInit/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(){
                                vm.reload();
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		saveOrUpdate: function () {
			var url = vm.pro.id_ == null ? "pro/deviceInit/save" : "pro/deviceInit/update";
			console.log(JSON.stringify(vm.pro));
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.pro),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		getPro: function(proId){
			$.get(baseURL + "pro/deviceInit/info/"+proId, function(r){
//				console.log(JSON.stringify(r.pro));
				vm.pro = r.pro;
				/*vm.pro.sickAreaName=r.pro.sickAreaName;
				vm.pro.sickAreaNO=r.pro.sickAreaNO;*/
                vm.getDeptUpdate();
                vm.getDeptSickUpdate();
			});
		},
	 
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择组织",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级组织
                    	vm.pro.deptId = node[0].deptId;
                        vm.pro.deptName = node[0].name;
                        if(vm.pro.sickAreaNO!=null){
                        	vm.pro.sickAreaNO=null;
                        	  vm.pro.sickAreaName=null;
                        }

                    layer.close(index);
                }
            });
        },
        deptTreeSick: function(){
        	if(vm.pro.deptId==null){
        		alert("请先选择组织");
        		return;
        	}
        	vm.getDeptSickUpdate();
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择病区",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayerSick"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztreeSick.getSelectedNodes();
                    //选择上级组织
                    if(node.length>0){
                    	  vm.pro.sickAreaNO = node[0].deptId;
                          vm.pro.sickAreaName = node[0].name;
                    }
                      
                    layer.close(index);
                }
            });
        },
		reload: function () {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                postData:{'bedNO': vm.q.bedNO},
                page:page
            }).trigger("reloadGrid");
		},
		exportTpl: function (url) {
			 
			var type=url.substring(url.lastIndexOf("/")+1);
			jQuery.jdownload(baseURL+url+'?token=' + token,'type="'+type+'"','post' );
		 
		},
		downloadData: function (url) {
			jQuery("#down_div").removeClass("xhide");
   			jQuery("#over_div").removeClass("xhide");
			 url+='?isData=1';
			var type=url.substring(url.lastIndexOf("/")+1);
			jQuery.jdownload(baseURL+url+'&token=' + token,'type="'+type+'"','post' );
			jQuery("#down_div").addClass('xhide');
			jQuery("#over_div").addClass('xhide');
		}
	}
});